package com.echoplots.jpa.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
@EnableJpaRepositories(basePackages = "com.echoplots.jpa.masterdao",
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanMaster",
        transactionManagerRef = "platformTransactionManagerMaster")
public class MasterJpaConfig {
    @Autowired
    @Qualifier(value = "dsMaster")
    DataSource dsMaster;

    @Autowired
    JpaProperties jpaProperties;

    @Bean
    @Primary
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanMaster(EntityManagerFactoryBuilder builder){
        return builder.dataSource(dsMaster)
                .properties(jpaProperties.getProperties())
                .packages("com.echoplots.jpa.entity")
                .persistenceUnit("puMaster")
                .build();

    }

    @Bean
    @Primary
    PlatformTransactionManager platformTransactionManagerMaster(EntityManagerFactoryBuilder builder){
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = localContainerEntityManagerFactoryBeanMaster(builder);
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean.getObject());
    }
}
